package com.xneure.utils.http;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicNameValuePair;

import com.xneure.utils.JsonUtil;


public class DefaultHttpHandler extends HttpDebugger<Object> {

	private boolean multiData = false;

	public DefaultHttpHandler(String urlServer,boolean isMultiForm) {
		this(urlServer);
		multiData = isMultiForm;
	}

	public DefaultHttpHandler(String urlServer) {
		super(HttpType.POST);
		setUrl(urlServer);
	}

	public void addBody(String name, Object obj) {
		addBody(name, JsonUtil.toJson(obj));
	}

	public void addBody(String name, String value) {
		getListEntity().add(new BasicNameValuePair(name, value));
	}

	public void setBody(Object obj) {
		setBody(JsonUtil.toJson(obj));
	}

	public void setBody(String value) {
		entity = new StringEntity(value, defaultType);
	}

	@SuppressWarnings("unchecked")
	public List<NameValuePair> getListEntity() {
		return (List<NameValuePair>) getEntity();
	}

	public HttpEntity getSimpleEntity() {
		return (HttpEntity) getEntity();
	}

	@Override
	public Object getEntity() {
		if (null == entity) {
			if (multiData) {
				entity = new ArrayList<NameValuePair>(20);
			}
			return entity;
		} else {
			return entity;
		}
	}

	@Override
	protected HttpEntity loadEntity() {
		if (multiData) {
			return new UrlEncodedFormEntity(getListEntity(), defaultCharset);
		} else {
			return getSimpleEntity();
		}
	}

}
